package com.watson.jpa.controller;

import com.watson.jpa.domain.User;
import com.watson.jpa.repository.UserRepository;
import com.watson.jpa.result.ObjectRestResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;

/**
 * @Description: TODO
 * @Author watson
 * @Date 2022/8/10 10:34
 * @Version 1.0
 */
@RestController
@RequestMapping("user")
public class UserController {
    @Autowired
    UserRepository userRepository;

    @GetMapping("insertUser/{name}")
    public ObjectRestResponse insertUser(@PathVariable(value = "name") String name) {
        User user = new User();
        user.setUsername(name);
        user.setPassword("123456");
        user.setRegdate(new Date());
        userRepository.save(user);
        return new ObjectRestResponse().msg("success");
    }

    @GetMapping("getUser")
    public ObjectRestResponse getUser() {
        List<User> all = userRepository.findAll();
        return new ObjectRestResponse(all).msg("success");
    }

    @GetMapping("getUserByEx")
    public ObjectRestResponse getUserBy() {
        User p = new User();
        p.setPassword("123456");
        Example<User> example2 = Example.of(p);
        User person2 = userRepository.findOne(example2).get();
        System.out.println("person2=" + person2.toString());
        List<User> list2 = userRepository.findAll(example2);
        System.out.println("personList2=" + list2.toString());

        p.setUsername("x");
        Example<User> example1 = Example.of(p);
        User person = userRepository.findOne(example1).get();
        System.out.println("person1=" + person.toString());
        List<User> list1 = userRepository.findAll(example1);
        System.out.println("personList1=" + list1.toString());

        //是以实体非空属性作为查询条件且以and连接的精确查询
        ExampleMatcher matcher = ExampleMatcher.matchingAll();
        Example<User> example3 = Example.of(p, matcher);
        List<User> list3 = userRepository.findAll(example3);
        System.out.println(list3.toString());

        return new ObjectRestResponse().msg("success");
    }
}
